package org.medusa.sample;

import org.medusa.network.tcp.BaseTcpSyncConnector;

//1.Sync与Async Connector互相转换的问题
//2.连接超时设置
public class SyncConnector extends BaseTcpSyncConnector<Packet> {

	private Packet half_packet_recv = null;
	
	public SyncConnector(int rcv_buf, int snd_buf) {
		super(rcv_buf, snd_buf);
		this.half_packet_recv = null;
	}

	@Override
	protected Packet parse_packet() {
		Packet pack = null;
		byte m;// byte //1:+ |2:- |3:* |4/
		short a;// A, B int16
		short b;
		short c;
		int len;
		short des;
		int uuid;
		boolean is_space_msg;
		int except_uuid;
		int notify_or_result;
		byte flag;

		
		if (this.half_packet_recv == null) {

			if (this.ringbuf.DataSize() < Packet.PACKET_HEAD_LEN) {
				return null;
			}
			m = this.ringbuf.ReadInt8(); // 1
			a = this.ringbuf.ReadInt16LE(); // 3
			b = this.ringbuf.ReadInt16LE(); // 5
			c = this.ringbuf.ReadInt16LE();// 7
			len = this.ringbuf.ReadInt32LE();// 11
			des = this.ringbuf.ReadInt16LE();// 13

			uuid = this.ringbuf.ReadInt32LE();// 17
			is_space_msg = this.ringbuf.ReadInt8() != 0;// 18
			except_uuid = this.ringbuf.ReadInt32LE();// 22
			notify_or_result= this.ringbuf.ReadInt32LE();// 26
			flag = this.ringbuf.ReadInt8();// 27

			pack = new Packet(m, a, b, c, len, des, uuid, is_space_msg,
					except_uuid, notify_or_result, flag);
			// pack.Show("recved:");
			if (this.ringbuf.DataSize() >= (pack.PacketSize() - Packet.PACKET_HEAD_LEN)) {
				pack.WriteBytes(this.ringbuf,
						(pack.PacketSize() - Packet.PACKET_HEAD_LEN));
				// pack.Show("Connector--PacketReceived");
			} else {
				this.half_packet_recv = pack;
				pack.WriteBytes(this.ringbuf, this.ringbuf.DataSize());
				pack = null;
			}
		} else {

			pack = this.half_packet_recv;
			int shengyu = pack.PacketSize() - pack.DataSize();

			if (this.ringbuf.DataSize() >= shengyu) {
				pack.WriteBytes(this.ringbuf, shengyu);
				this.half_packet_recv = null;
				// pack.Show("Acceptor--PacketReceived")
			} else {
				pack.WriteBytes(this.ringbuf, this.ringbuf.DataSize());
				pack = null;
			}
		}// end of :if (this.half_packet_recv == null)...else...

		return pack;
	}

}
